package com.zxdemo.service.imp;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.zxdemo.jpa.model.Menu;
import com.zxdemo.mybatis.dao.MenuMapper;
import com.zxdemo.mybatis.dao.UserMapper;
import com.zxdemo.service.MenuService;
@Service("menuService")
public class MenuServiceImpl implements MenuService{
	@Autowired
	private MenuMapper menuMapper;
	@SuppressWarnings("unused")
	@Autowired
	private UserMapper userMapper;
	@Override
	public List<Menu> queryListParentId(Long parentId,List<Long> menuIdList) {
		List<Menu> menuList = menuMapper.queryListParentId(parentId);
		if(menuIdList == null){
			return menuList;
		}
		
		List<Menu> userMenuList = new ArrayList<>();
		for(Menu menu : menuList){
			if(menuIdList.contains(menu.getMenuId())){
				userMenuList.add(menu);
			}
		}
		return userMenuList;
	}

	@Override
	public List<Menu> queryNotButtonList() {
		// TODO Auto-generated method stub
		return menuMapper.queryNotButtonList();
	}

	@Override
	public int queryTotal() {
		// TODO Auto-generated method stub
		return menuMapper.queryTotal();
	}

	@Override
	public void save(Menu menu) {
		// TODO Auto-generated method stub
		menuMapper.save(menu);
	}

	@Override
	public void update(Menu menu) {
		// TODO Auto-generated method stub
		menuMapper.update(menu);
	}

	@Override
	public void deleteBatch(List<Long> menuIdList) {
		// TODO Auto-generated method stub
		menuMapper.deleteBatch(menuIdList);
	}

	@Override
	public Menu queryObject(Long menuId) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public List<Menu> queryList(Integer offset, Integer limit) {
		// TODO Auto-generated method stub
		return null;
	}
	
	
	
	/**
	 * 获取子菜单
	 */
	private List<Menu> getMenu(Long rootId,List<Menu> menuList){
		List<Menu> result = new ArrayList<Menu>();
		//遍历菜单
		for(Menu entity:menuList){
			Long menuId=entity.getMenuId();
			Long parentId=entity.getParentId();
			if(parentId>=0)
			{
				if(parentId.equals(rootId))
				{
					List<Menu> chilidMenu=getMenu(menuId, menuList);
					entity.setChild(chilidMenu);
					result.add(entity);
				}
			}
			
		}
		
		return result;
	}
	
	
	
	
	
	@Override
	public List<Menu> getUserMenuList(Long userId) {
		
		//系统管理员，拥有最高权限
		if(userId == 1L){
			List<Menu> allMenu =menuMapper.queryNotButtonList();
			List<Menu> adminMenu=getMenu(0L, allMenu);
			return adminMenu;
		}
		//用户菜单列表
		List<Menu> userMenuIdList =menuMapper.queryListByUserId(userId);
		System.out.println(JSON.toJSONString(userMenuIdList));
		List<Menu> userMenu=getMenu(0L, userMenuIdList);
		return userMenu;
	}

}
